//
//  ListTrainController.swift
//  AirTravel
//
//  Created by apple on 2021/8/10.
//

import UIKit
import FWPopupView
import Moya
import SwiftyJSON

class ListTrainController: UIViewController {

    @IBOutlet weak var tabView: UITableView!
    @IBOutlet weak var timeLab: UILabel!
    
    @IBOutlet weak var bottomView: UIView!
    /// 价格
    @IBOutlet weak var priceBtn: UIButton!
    /// 耗时
    @IBOutlet weak var consumingBtn: UIButton!
    /// 出发
    @IBOutlet weak var setOutBtn: UIButton!
    /// 筛选
    @IBOutlet weak var screeningBtn: UIButton!
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    
    let identifyLT = "ListTrainCell"
    var dataStr = ""
    var according = ""
    var difference = "今天"
    /// 出发站名称
    var fromStationName = ""
    /// 到达站名称
    var toStationName = ""
    /// 是否支持学生票 0全部 1是
    var isStudent = 0
    /// 只看高铁动车 0查看全部 1只看高铁动车
    var isHigh = 0
    /// 车次类型 0全部 1高铁G/C 2动车D 3普通Z/T/K 4其他Y/L等
    var trainType = 0
    /// 车次类型 0全部 1 00:00-06:00 2 06:00-12:00 3 12:00-18:00 4 18:00:-24:00
    var timeType = 0
    /// 时间排序 1正序 2逆序
    var timeSort = 0
    /// 耗时排序 1正序 2逆序
    var durationSort = 0
    /// 价格排序 1正序 2逆序
    var priceSort = 0
    var dataSouce : Array<Any>?
    var stationNameList : Array<Any>?
    var stationName = ""
    /// 0选车，，1改签
    var type = 0
    
    
    
    lazy var radioTimeView: RadioTimeView = {
        let customPopupView = RadioTimeView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 450))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.clear
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "1"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    lazy var trainTicketView: TrainTicketScreeningView = {
        let customPopupView = TrainTicketScreeningView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT * 0.8))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.clear
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "1"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    //视图将要显示
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
        //设置导航栏背景透明
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(),
                                                                    for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
    }
         
    //视图将要消失
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //重置导航栏背景
        self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        self.navigationController?.navigationBar.shadowImage = nil
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "\(self.fromStationName)-\(self.toStationName)"
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "ListTrainCell", bundle: nil), forCellReuseIdentifier: identifyLT)
        self.tabView.separatorStyle = .none
        self.tabView.ly_emptyView = LYEmptyView.empty(withImageStr: "无数据、空数据", titleStr: "", detailStr: "暂无任何内容~")
        
        
        self.bottomView.layer.cornerRadius = 25
        self.bottomView.layer.masksToBounds = true
        
        self.timeLab.text = self.according + "  \(self.difference)"
        self.tabView.es.addPullToRefresh {
            [unowned self] in
            /// 在这里做刷新相关事件
            self.searchTrainsBetweenStations()
            /// 如果你的刷新事件成功，设置completion自动重置footer的状态
            self.tabView.es.stopPullToRefresh()
            /// 设置ignoreFooter来处理不需要显示footer的情况
            self.tabView.es.stopPullToRefresh(ignoreDate: true, ignoreFooter: true)
        }
        self.tabView.es.startPullToRefresh()
    }

    //查询站站车次列表接口
    func searchTrainsBetweenStations() {
        
        print("\(["departDate":self.dataStr,"fromStationName":self.fromStationName,"toStationName":self.toStationName,"isStudent":self.isStudent,"isHigh":self.isHigh,"trainType":self.trainType,"timeType":self.timeType,"timeSort":self.timeSort,"durationSort":self.durationSort,"priceSort":self.priceSort,"stationName":self.stationName])")
        
        cancelableRequest = NetWorkRequest(API1.searchTrainsBetweenStations(parameters: ["departDate":self.dataStr,"fromStationName":self.fromStationName,"toStationName":self.toStationName,"isStudent":self.isStudent,"isHigh":self.isHigh,"trainType":self.trainType,"timeType":self.timeType,"timeSort":self.timeSort,"durationSort":self.durationSort,"priceSort":self.priceSort,"stationName":self.stationName]), completion: {[weak self] (responseString) -> (Void) in
            self?.dataSouce = responseString["data"]["list"].arrayObject
            self?.stationNameList = responseString["data"]["stationNameList"].arrayObject
            self?.tabView.reloadData()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            
            YProgressHUD.showToast("当天无直达")
            print("网络异常")
        })
    }
    
    //切换时间
    @IBAction func screeningBtn(_ sender: UIButton) {
        self.radioTimeView.setUpData(str: self.dataStr)
        self.radioTimeView.show()
    }
    //前一天
    @IBAction func beforeBtn(_ sender: Any) {
        self.computationTime(i: -1)
    }
    //后一天
    @IBAction func afterBtn(_ sender: Any) {
        self.computationTime(i: 1)
    }
    
    @IBAction func bottomBtn(_ sender: UIButton) {
        switch sender.tag {
        case 0:
            self.trainTicketView.setUpdata(stationNameList: self.stationNameList ?? [])
            self.trainTicketView.show()
        case 1:
            self.priceSort = 0
            self.durationSort = 0
            switch self.timeSort {
            case 0:
                self.timeSort += 1
                self.setOutBtn.setImage(UIImage.init(named: "多边形1拷贝-1"), for: .normal)
            case 1:
                self.timeSort += 1
                self.setOutBtn.setImage(UIImage.init(named: "多边形1拷贝4"), for: .normal)
            case 2:
                self.timeSort = 0
                self.setOutBtn.setImage(UIImage.init(named: "多边形1拷贝3-1"), for: .normal)
            default:
                break
            }
        case 2:
            self.priceSort = 0
            self.timeSort = 0
            switch self.durationSort {
            case 0:
                self.durationSort += 1
                self.consumingBtn.setImage(UIImage.init(named: "多边形1拷贝-1"), for: .normal)
            case 1:
                self.durationSort += 1
                self.consumingBtn.setImage(UIImage.init(named: "多边形1拷贝4"), for: .normal)
            case 2:
                self.durationSort = 0
                self.consumingBtn.setImage(UIImage.init(named: "多边形1拷贝3-1"), for: .normal)
            default:
                break
            }
        case 3:
            self.durationSort = 0
            self.timeSort = 0
            switch self.priceSort {
            case 0:
                self.priceSort += 1
                self.priceBtn.setImage(UIImage.init(named: "多边形1拷贝-1"), for: .normal)
            case 1:
                self.priceSort += 1
                self.priceBtn.setImage(UIImage.init(named: "多边形1拷贝4"), for: .normal)
            case 2:
                self.priceSort = 0
                self.priceBtn.setImage(UIImage.init(named: "多边形1拷贝3-1"), for: .normal)
            default:
                break
            }
        default:
            break
        }
        searchTrainsBetweenStations()
    }
    
    
    func computationTime(i:Int) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let jtStr = dateFormatter.string(from: Date())
        guard let date1 = dateFormatter.date(from: jtStr) else { return }
        
        guard let today = dateFormatter.date(from: self.dataStr) else { return }
        let tomorrow = Calendar.current.date(byAdding: .day, value: i, to: today)
        let dataStr = dateFormatter.string(from: tomorrow!)
        dateFormatter.dateFormat = "MM月dd日"
        let according = dateFormatter.string(from: tomorrow!)
        let components = NSCalendar.current.dateComponents([.day], from: date1, to: tomorrow!)
        let components1 = NSCalendar.current.dateComponents([.weekday], from: tomorrow!)
        var difference = ""
        if components.day! < 0 {
            YProgressHUD.showToast("日期不能小于今天")
            return
        }
        if components.day == 0{
            difference = "今天"
        }else if components.day == 1 {
            difference = "明天"
        }else{
            switch components1.weekday {
            case 1:
                difference = "周日"
            case 2:
                difference = "周一"
            case 3:
                difference = "周二"
            case 4:
                difference = "周三"
            case 5:
                difference = "周四"
            case 6:
                difference = "周五"
            case 7:
                difference = "周六"
            default:
                break
            }
        }
        self.dataStr = dataStr
        self.according = according
        self.difference = difference
        self.timeLab.text = self.according + "  \(self.difference)"
        self.dataSouce?.removeAll()
        self.tabView.reloadData()
        self.searchTrainsBetweenStations()
    }
}

extension ListTrainController:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSouce?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifyLT) as! ListTrainCell
        cell.selectionStyle = .none
        if let array = self.dataSouce {
            let dic = array[indexPath.row] as? Dictionary<String,Any>
            cell.setUpData(dic: dic ?? [:])
            
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 105
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if let array = self.dataSouce {
            let dic = array[indexPath.row] as? Dictionary<String,Any>
            let trainNo = "\(dic?["trainNo"] ?? "")"
            let vc = ServiceDetailsController()
            vc.according = self.according
            vc.dataStr = self.dataStr
            vc.difference = self.difference
            vc.trainNo = trainNo
            vc.fromStationName = self.fromStationName
            vc.toStationName = self.toStationName
            vc.type = self.type
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
}

extension ListTrainController:RadioTimeDelegate{
    func radioTimeClick(date: String, according: String, difference: String) {
        self.dataStr = date
        self.according = according
        self.difference = difference
        self.timeLab.text = self.according + "  \(self.difference)"
        self.dataSouce?.removeAll()
        self.tabView.reloadData()
        self.searchTrainsBetweenStations()
    }
}

extension ListTrainController:TicketScreeningDelegate{
    func ticketScreeningClick(dic: Dictionary<String, Any>) {
        
        self.trainType = Int("\(dic["trainType"] ?? "0")") ?? 0
        self.timeType = Int("\(dic["timeType"] ?? "0")") ?? 0
        self.stationName = "\(dic["stationName"] ?? "")"
        self.searchTrainsBetweenStations()
    }
}
